//
//  RootViewController.m
//  evidenceGather
//
//  Created by 继伟 王 on 13-8-17.
//  Copyright (c) 2013年 无. All rights reserved.
//

#import "RootViewController.h"
#import "EvidenceBrowseViewController.h"

#import "RequestTccInfo.h"


#import "MDUser.h"
#import "MDProbCls.h"
#import "MDProject.h"
#import "MDProvince.h"
#import "UserVO.h"



@implementation RootViewController

@synthesize userName = _userName;
@synthesize passWard = _passWard;

//登录按钮工作
- (IBAction)loginBtn:(id)sender {
    
    
    
    //获取用户录入信息,11
    UserVO * userVO=[[UserVO alloc] init] ;
    [userVO setLoginuser:_userName.text];
    [userVO setPwd:_passWard.text];
    [userVO setServerIP:_serverIP.text];
    [userVO setServerPort:_serverport.text];
    [userVO setAlamMinSpace:_alarmNum.text];
    
    RequestTccInfo *reqeustProv=[[RequestTccInfo alloc] init];
    
    //构建服务器信息
    NSString *serverInfo=userVO.serverIP;
    serverInfo=[serverInfo stringByAppendingFormat:@":%@",userVO.serverPort ];
    reqeustProv.serverInfo = serverInfo;
    
    //远程校验用户身份
    int validtFlag=[reqeustProv loginValidate:userVO.loginuser pwd:userVO.pwd];
    Boolean flag=false;
    
    MDUser *mdUser=[[MDUser alloc] init];
    
    //如果登录成功
    if(validtFlag > 0){
        UserVO *curUser = [mdUser qryUserByUser:userVO.loginuser];
        if (nil == curUser) {
            [mdUser insertUserVO:userVO];
        }else{
            [mdUser updateUser:userVO];
        }
        
        //同步最新用户密码
        [reqeustProv UserSynchronous:userVO.loginuser pwd:userVO.pwd];
        
        //获取省份信息
        MDProvince *mdProvice=[[MDProvince alloc] init];
        NSArray *provinceVos= [reqeustProv getProvinceInfo:userVO.loginuser pwd:userVO.pwd];
        if(nil != provinceVos && provinceVos.count > 0)
        {
            //更新本地省份信息
            [mdProvice update:provinceVos];
            
            //项目信息
            MDProject *mdProject=[[MDProject alloc] init];
            //根据省份，循环查询项目信息（效率比较低），后续建议改进接口
            for (int i = 0; i < provinceVos.count; i++) {
                ProviceVO *prvo = [provinceVos objectAtIndex:i];
                
                //查询该省分对应的本地缓存项目
                NSMutableDictionary *padProjs = [mdProject qryProjectByPkPrvcode:[prvo prvcode]];
                /*
                    待补充
                 */
                
                
                NSArray *projectVOs=[reqeustProv GetProjectInfoByProvince:userVO.loginuser pwd:userVO.pwd projcode:nil provcode:[prvo prvcode]];
               
                [mdProject update:projectVOs];
            }
        }
        
        NSArray *probClsVos=[reqeustProv getQuestTypeWithUser:userVO.loginuser];
        
         //更新问题分类至本地，如果本地没有，则新增
        MDProbCls *mdProbCl=[[MDProbCls alloc] init];
       
        if(nil != probClsVos && probClsVos.count > 0)
        {
             [mdProbCl update:probClsVos];
        }
        flag=true;
                
    }else{
//      如果远程验证
        UserVO *tempUserVO=[mdUser qryUserByUser:userVO.loginuser];
        if(tempUserVO!=nil){
            //如果登录失败，但是老密码与客户端密码相同，则可以完成登陆，并同步新密码到客户端
            if([userVO.pwd compare:tempUserVO.pwd options:NSLiteralSearch]==NSOrderedSame){
                //更新用户信息
                [mdUser updateUser:userVO];
                flag=true;
            }
        }
    }
    
    //如果登录成功，则同步项目，省份、问题分类
    if(flag){
        
        EvidenceBrowseViewController *secondStepViewController=[[EvidenceBrowseViewController alloc] initWithNibName:@"EvidenceBrowseViewController" bundle:nil];
        
        [secondStepViewController setUserVO:userVO];

        [self presentModalViewController:secondStepViewController animated:YES];
    }else{
        
        UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"登陆失败" message:@"用户名或密码错误" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    }
    
}


- (IBAction)loginViewBtn:(id)sender {
    [_settingView setHidden:YES];
    [_loginView setHidden:NO];
}

- (IBAction)setViewBtn:(id)sender {
    [_settingView setHidden:NO];
    [_loginView setHidden:YES];
    
}
- (IBAction)saveSettBtn:(id)sender {
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImage *image =[UIImage imageNamed:@"login_bg.png"];
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:image]];
    
    image =[UIImage imageNamed:@"login_layer.png"];
    [_loginView setBackgroundColor:[UIColor colorWithPatternImage:image]];
    image =[UIImage imageNamed:@"login_layer2.png"];
    [_settingView setBackgroundColor:[UIColor colorWithPatternImage:image]];
    [_loginView setFrame:CGRectMake(58, 215, 652, 485)];
    [_settingView setFrame:CGRectMake(58, 215, 652, 485)];
    [_settingView setHidden:YES];
    [_passWard setSecureTextEntry:YES];
    MDUser *mdUser=[[MDUser alloc] init];
    UserVO *lastUser = mdUser.qryUserLastLogin;
    if(nil != lastUser)
    {
        _userName.text = lastUser.loginuser;
        _serverIP.text = lastUser.serverIP;
        _serverport.text = lastUser.serverPort;
        _alarmNum.text = lastUser.alamMinSpace;
        
//        _passWard.text=lastUser.pwd;  //comment by sijian for: don't display the pwd.
        _passWard.placeholder=@"密码";

    }else{
        _userName.placeholder=@"用户";
        _passWard.placeholder=@"密码";
        _serverIP.placeholder=@"服务器地址";
        _serverport.placeholder=@"服务器端口";
        _alarmNum.placeholder=@"内存预警数量";
    }
    mdUser = nil;
}

- (void)viewDidUnload
{
    [self setUserName:nil];
    [self setPassWard:nil]; 
    [self setServerIP:nil];
    [self setServerport:nil];
    [self setAlarmNum:nil];
    [self setLoginView:nil];
    [self setSettingView:nil];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return YES;
}


- (void)dealloc { 
    [_serverIP release];
    [_serverport release];
    [_alarmNum release];
    [_loginView release];
    [_settingView release];
    [super dealloc];
}

@end
